<?php
namespace app\cash\controller;
use think\Controller;
use think\Db;
use app\cash\model\OrderDetails;
use app\cash\model\StoreGoodsLog;
class Guadan20180910 extends Controller{
    /**
     * @Author lignyun
     * @Desc    检查登录
     * 2018-04-09
     */
    public function _initialize(){
        if(!session('cash_user')) {
            $this->redirect('@cash/login/index');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    挂单
     * 2018-06-11
     */
    public function index(){
        $post = input('post.');
        $store_id = session('cash_user')['store_id'];
        $store = $this->get_store($store_id);
        $member = $this->get_member($post['mobile'],$post['uid']);

        if(empty($post['mobile']) && !empty($post['yue'])){
            $this->error('请查询会员信息，再使用余额付款','');
        }
        $this->create_goods($post,$store_id,$member,$store);
    }

    /**
     * @Author  lingyun
     * @Desc    生成订单记录
     *          ys_order
     *          ys_order_details
     *          ys_order_action
     *          ys_pay_log
     *          ys_user
     *          ys_user_wallet_log
     *          ys_user_point_log
     *          ys_store
     *          ys_store_credit_log
     *          ys_store_goods_stock
     *          ys_store_goods_log
     */
    private function create_goods($post,$store_id,$member,$store){
        $goods_id = $post['goods_id'];
        $goods_spec_id = $post['goods_spec_id'];
        $goods_num = $post['goods_num'];
        $goods_discount = $post['goods_discount'];
        $s_goods_amount = $post['s_goods_amount'];          //商品改价
        $sn = 'L' . build_order_no();           //订单号
        $uid = empty($member)?0:$member['uid'];
        $mobile = empty($member)?'':$member['mobile'];

        $order_goods_details = [];          //订单详情
        $final_amount = 0;                  //最终支付价
        $discount_amount = 0;                  //折扣价
        $all_num = array_sum($goods_num);       //所有的商品数量
        $store_goods_stock_arr = [];            //商品库存日志记录

        $coupon_info = $this->get_coupon($post['coupon_id'],$all_num);
        $coupon = $coupon_info['coupon'];               //优惠券信息
        $coupon_signal_price = $coupon_info['coupon_signal_price'];     //平摊优惠券价格

        $chengben = 0;              //商品成本价
        $chengben_price = 0;        //商品销售成本价


        $receipt = '';          //线下小票信息
        $receipt .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号：'.$sn.'</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员：' . session("cash_user")["realname"] . '</td></tr><tr><td colspan="4" style="text-align: center">—————————————————————</td></tr><tr><td style="width: 10mm;">商品</td><td>数量</td><td>单价</td><td>金额</td><td>折扣</td></tr>';

        foreach($goods_id as $k => $v){
            $map['a.goods_id'] = ['eq',$v];
            $map['a.goods_spec_id'] = ['eq',$goods_spec_id[$k]];
            $map['a.store_id'] = ['eq',$store_id];

            $goods_result = $this->get_goods($map,$store,$goods_num[$k],$member,$goods_discount[$k],$s_goods_amount[$k]);       //获取商品信息
            $goods_discount[$k] = $goods_result['goods_discount'];                  //商品折扣
            $discount_signal_price= $goods_result['discount_signal_price'];         //商品折扣单价
            $goods = $goods_result['goods'];                                        //商品详情信息

            $chengben = $chengben+$goods['chengben'];                               //成本
            $chengben_price = $chengben_price+$goods['chengben_price'];                   //销售成本

            $arr = $this->create_order_detail($uid,$store_id,$goods,$goods_num[$k],$goods_discount[$k],$coupon_signal_price,$discount_signal_price);                            //创建订单详情记录

            array_push($order_goods_details,$arr);      //订单详情记录

            $store_goods_stock_arr[$k] =$this->create_goods_stock_log($store_id,$goods,$goods_num[$k],$sn);     //商品库存记录

            $final_amount = $final_amount + $goods['final_amount']*$goods_num[$k] ;             //订单总价
            $discount_amount =  $discount_amount + $discount_signal_price*$goods_num[$k];       //折扣总金额

            $ffinal_amount = $final_amount-$discount_amount-$coupon['reduce'];              //最终支付金额

            $receipt .= '<tr style="font-size: smaller;width: 25mm;"><td colspan="4" style="text-align: left">' . $goods["name"].' '.$goods["title"]. '</td></tr><tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $goods_num[$k] . '</td><td>' . $goods["final_amount"] . '</td><td>' . $goods["final_amount"]*$goods_num[$k] . '</td><td>' . $goods_discount[$k] . '</td></tr>';

        }

        $receipt .= '<tr><td colspan="4" style="text-align: left">—————————————————</td></tr>';

        $receipt .= '<tr><td colspan="2" style="text-align: left;font-size: smaller">总计：' . $final_amount.'</td><td colspan="2" style=";text-align: center;font-size: smaller;">折扣：'.$discount_amount.'</td></tr>';

        $receipt .= '<tr><td colspan="2" style="text-align: left;font-size: smaller">实收：' . $ffinal_amount.'</td><td colspan="2" style="text-align: left;font-size: smaller">优惠券：' . $coupon["reduce"].'</td></tr>';


//        if(!empty($member)){            //显示会员信息
//            if($post['yue'] <= $final_amount-$coupon['reduce']-$discount_amount){         //余额付款
//                $user_money = $member['user_money'] - $post['yue'];
//            }else{
//                $user_money = $member['user_money'] - $final_amount-$coupon['reduce']-$discount_amount;
//            }
//
//            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：￥' . $member["mobile"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
//            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $user_money . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
//        }
//        $receipt .= '<tr><td colspan="4" style="text-align: left">' . $store["address"] . '</td></tr>';
//        $receipt .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
//        $receipt .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';


        $pay_status = 0;
        $remark = '订单待支付';
        $order_status = 0;

        //订单信息
        $order_arr = [
            'uid'=>$uid,
            'coupon_id'=>$post['coupon_id'],
            'coupon_price'=>$coupon['reduce'],
            'order_type'=>0,
            'order_sn'=>$sn,
            'store_id'=>$store_id,  //门店id
            'mobile'=>$mobile,
            'pay_type'=>0,
            'pay_type_two'=>0,          //余额支付部分
            'pay_status'=>$pay_status,
            'order_status'=>$order_status,
            'goods_num'=>$all_num,
            'goods_price'=>$final_amount,
            'order_amount'=>$ffinal_amount,
            'receipt'=>$receipt,
            'final_amount'=>$ffinal_amount,
            'discount_amount'=>$discount_amount,
            'addtime'=>time(),
            'cashier'=>session('cash_user')['id'],
            'chengben'=>$chengben,
            'chengben_price'=>$chengben_price,
            'is_guadan'=>1,
        ];

        $order_id = db('order')->insertGetId($order_arr);

        foreach ($order_goods_details as $k => $v) {
            if($v['discount_num'] == '无'){
                $order_goods_details[$k]['discount_num'] = 0;
            }
            $order_goods_details[$k]['status'] = $order_status;
            $order_goods_details[$k]['order_id'] = $order_id;
        }

        $orderdetailsmodel = new OrderDetails();
        $orderdetailsmodel->insertAll($order_goods_details);            //插入订单详情记录
        $order_action = [
            'uid' => $uid,
            'order_id' => $order_id,
            'action_user' => 0,
            'order_status' => $order_status,
            'pay_status' => $pay_status,
            'status_desc' => $remark,
            'storeid' => $store_id,
            'addtime' => time(),
        ];
        db('order_action')->insert($order_action);                      //订单动作记录

        $this->success('挂单成功','');

    }

    /**
     * @Author  lingyun
     * @Desc    获取商品信息
     * 2018-06-09
     */
    private function get_goods($map,$store,$goods_num,$member,$goods_discount,$goods_final_amount){
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where($map)->field('a.id,a.goods_id,a.goods_spec_id,a.stock,is_diannei,a.trim_price,b.name,b.member_level_id,a.is_deleted,a.onsale,c.title,c.price,c.member_price,c.peifang_ids,a.chengben,a.chengben_price')->find();

        $chengben_result = $this->get_chengben($goods['peifang_ids'],$goods['chengben'],$goods['chengben_price']);
        $goods['chengben'] = $goods_num*$chengben_result['chengben'];
        $goods['chengben_price'] = $goods_num*$chengben_result['chengben_price'];

        if($goods['onsale'] == 0 || $goods['is_deleted'] ==1){
            $this->error($goods['name'].$goods['title'].'已下架，请重新选择商品','');
        }else if($goods['stock'] < $goods_num){
            $this->error($goods['name'].$goods['title'].'库存不足，请重新选择商品','');
        }

//        if($store['price_status'] == 1 && $goods['trim_price'] !=0){
//            $goods['final_amount'] = $goods['trim_price'];
//        }else if(!empty($member)){
//            if($member['level_id'] >= $goods['member_level_id']){
//                $goods['final_amount'] = $goods['member_price'];
//            }
//        }else{
//            $goods['final_amount'] = $goods['price'];
//        }

        $goods['final_amount'] = $goods_final_amount;

        if($goods_discount != 0){      //折扣
            $discount_signal_price = $goods['final_amount']*(10-$goods_discount)/10;
            $goods_discount = $goods_discount;

        }else{
            $goods_discount = '无';
            $discount_signal_price = 0;
        }

        return ['goods'=>$goods,'discount_signal_price'=>$discount_signal_price,'goods_discount'=>$goods_discount];
    }

    /**
     * @Author  lingyun
     * @Desc    计算成本
     * 2018-06-09
     */
    private function get_chengben($peifang_ids,$chengben,$chengben_price){
        if(empty($chengben) || empty($chengben_price)){         //没有成本价
            if(empty($peifang_ids)){
                $chengben = 0;
                $chegnben_price = 0;
            }
            $peifang = db('goods_peifang')->where('id','in',$peifang_ids)->field('chengben,chengben_price')->select();

            $chengben = array_sum(array_map(function($peifang){return $peifang['chengben'];}, $peifang));
            $chengben_price = array_sum(array_map(function($peifang){return $peifang['chengben_price'];}, $peifang));
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }else{
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }
    }

    /**
     * @Author  lingyun
     * @Desc    创建订单详情记录
     */
    private function create_order_detail($uid,$store_id,$goods,$goods_num,$discount_num,$coupon_signal_price,$discount_signal_price){
        $arr['uid'] = $uid;
        $arr['spec_id'] = $goods['goods_spec_id'];
        $arr['spec_detail'] = $goods['title'];
        $arr['goods_id'] = $goods['goods_id'];
        $arr['goods_num'] = $goods_num;
        $arr['spec_price'] = $goods['final_amount'];
        $arr['coupon_price'] = $coupon_signal_price;
        $arr['discount_signal_price'] = $discount_signal_price;
        $arr['discount_num'] = $discount_num;
        $arr['all_discount_prcie'] = $discount_signal_price+$coupon_signal_price;
        $arr['goods_amount'] = $goods_num*$goods['final_amount'];
        $arr['final_amount'] = $goods['final_amount']*$goods_num-$discount_signal_price*$goods_num-$coupon_signal_price*$goods_num;
        $arr['storeid'] = $store_id;
        $arr['is_online'] = 0;
        $arr['store_goods_stock_id'] = $goods['id'];
        $arr['addtime'] = time();
        $arr['chengben'] = $goods['chengben'];
        $arr['chengben_price'] = $goods['chengben_price'];


        return $arr;
    }

    /**
     * @Author  lingyun
     * @Desc    创建商品库存记录
     */
    private function create_goods_stock_log($store_id,$goods,$goods_num,$sn){
        //门店库存记录数据
        $store_goods_stock_arr['goods_id'] = $goods['goods_id'];
        $store_goods_stock_arr['goods_spec_id'] = $goods['goods_spec_id'];
        $store_goods_stock_arr['title'] = '';
        $store_goods_stock_arr['store_id'] = $store_id;
        $store_goods_stock_arr['order_id'] = '';
        $store_goods_stock_arr['types'] = 2;
        $store_goods_stock_arr['ruku_num'] = 0;
        $store_goods_stock_arr['tuihuo_num'] = 0;
        $store_goods_stock_arr['chuku_num'] = $goods_num;
        $store_goods_stock_arr['sunhao_num'] = 0;
        $store_goods_stock_arr['remark'] = '售卖'.$goods_num;
        $store_goods_stock_arr['cur_stock'] = $goods['stock'] - $goods_num;
        $store_goods_stock_arr['addtime'] = time();
        $store_goods_stock_arr['order_sn'] = $sn;

        return $store_goods_stock_arr;
    }

    /**
     * @Author  lingyun
     * @Desc    获取会员信息
     * 2018-06-08
     */
    private function get_member($mobile,$uid){
        if(empty($mobile)){
            return array();
        }else{
            $member = db('user')->where('mobile',$mobile)->field('uid,user_money,realname,mobile,pay_code,level_id')->find();
            if(!empty($member)){
                if($member['uid'] != $uid){
                    $this->error('请先查询会员信息','');
                }
                return $member;
            }else{
                $member = db('user')->where('pay_code',$mobile)->field('uid,user_money,realname,mobile,pay_code,level_id')->find();
                if(empty($member)){
                    return array();
                }else{
                    if($member['uid'] != $uid){
                        $this->error('请先查询会员信息','');
                    }
                    return $member;
                }
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    获取门店信息
     * 2018-06-08
     */
    private function get_store(){
        $store_id = session('cash_user')['store_id'];
        $store = db('store')->where('id',$store_id)->find();

        return $store;
    }

    /**
     * @Author  lingyun
     * @Desc    获取优惠券信息
     * 2018-06-09
     */
    private function get_coupon($coupon_id,$all_num){
        $coupon = db('user_ycard')->where('coupon_id',$coupon_id)->find();
        if(empty($coupon)){
            $coupon_signal_price = 0;
            $coupon['reduce'] = 0;
            $coupon['id'] = 0;
        }else{
            $coupon_signal_price = sprintf("%.2f",substr(sprintf("%.3f", $coupon['reduce']/$all_num), 0, -1));
        }

        return ['coupon'=>$coupon,'coupon_signal_price'=>$coupon_signal_price];
    }

    /**
     * @Author  lingyun
     * @Desc    获取挂单列表信息
     * 2018-06-11
     */
    public function get_order_list(){
        $store_id = session('cash_user')['store_id'];
        $map['pay_status'] = ['eq',0];
        $map['store_id'] = ['eq',$store_id];
        $map['is_guadan'] = ['eq',1];
        $order_sn = input('key');
        if(!empty($order_sn)){
            $map['order_sn'] = ['eq',$order_sn];
        }
        $order = db('order')->where($map)->field('order_sn,id,final_amount,addtime')->order('id desc')->select();

        $this->assign('key',$order_sn);
        $this->assign('order',$order);

        return $this->fetch('account');
    }

    /**
     * @Author  lingyun
     * @Desc    获取订单信息
     */
    public function get_order_details(){
        $order_id = input('order_id');
        $order = db('order')->where('id',$order_id)->find();
        if($order['pay_type'] == 1){
            $this->error('该订单已支付，请勿重复支付','');
        }
        if(!empty($order['uid'])){
            $member = db('user')->where('uid',$order['uid'])->find();
        }else{
            $member = array();
        }

        $sql = "select case when LENGTH(b.name) < 20 then b.name else CONCAT(left(b.name,20),'...') end as name, case when LENGTH(a.spec_detail) < 20 then a.spec_detail else CONCAT(left(a.spec_detail,20),'...') end as spec_detail,a.spec_price,a.goods_num,a.all_discount_prcie,a.discount_num  from ys_order_details as a left join ys_goods as b on a.goods_id=b.id where a.order_id=".$order_id;

        $list = Db::query($sql);

        if(!empty($list)){
            $this->success('查询成功','',['list'=>$list,'member'=>$member,'final_amount'=>$order['final_amount'],'order_id'=>$order['id']]);
        }else{
            $this->error('找不商品信息','');
        }

    }

    /**
     * @Author  lingyun
     * @Desc    支付订单
     */
    public function pay(){
        $post = input('post.');

        $order = db('order')->where('id',$post['order_id'])->find();        //订单详情

        if(empty($order)){          //找不到订单信息
            $this->error('找不到订单信息，请重试','');
        }else if($order['pay_status'] != 0){
            $this->error('该订单已支付，请勿重复支付','');
        }

        if(empty($order['uid']) && $post['yue'] > 0){
            $this->error('该订单选中会员信息，不能使用余额支付','');
        }

        $member = db('user')->where('uid',$order['uid'])->find();
        $store = db('store')->where('id',$order['store_id'])->find();
        if(!empty($member)){
            if($post['yue'] > $member['user_money']){
                $this->error('使用余额不能超过会员的可用余额','');
            }
        }


        //判断支付方式
        if(empty($post['yue'])){           //判断付款方式，余额够用则只有余额付款，其它表示组合付款
            $pay_type = $post['pay_type'];
            if(empty($pay_type)){
                $this->error('请选择付款方式','');
            }

            $pay_type_two = 0;
            if($pay_type == 4 || $pay_type == 5 || $pay_type == 6 || $pay_type == 7){       //现金、银行卡、美团、饿了么
                $pay_status = 1;
                $order_status = 4;
                $remark = '订单已完成';
            }else{
                $pay_status = 0;
                $pay_type_two = 0;
                $remark = '订单待支付';
            }
        }else if($post['yue'] > $order['final_amount']){      //余额付款
            $pay_type = 3;      //余额付款
            $pay_type_two = 0;
            $pay_status = 1;
            $order_status = 4;
            $remark = '订单已完成';
        }else{          //组合付款
            $pay_type = $post['pay_type'];
            if(empty($pay_type)){
                $this->error('请选择支付方式','');
            }

            $pay_type_two = $post['yue'];           //组合付款使用余额
            if($pay_type == 4 || $pay_type == 5 || $pay_type == 6 || $pay_type == 7){
                $pay_status = 1;
                $order_status = 4;
                $remark = '订单已完成';
            }else{
                $pay_status = 0;
                $order_status = 0;
                $remark = '订单待支付';
            }
        }

        if($store['is_jiameng'] == 1){              //加盟店
            $remark = '订单已完成';
            $pay_status = 1;
            $order_status = 4;
        }

        if($pay_status == 1){           //订单已完成
            $receipt = $order['receipt'];
            if($pay_type_two == 0){
                $use_yue = '';
                $pty = $order['final_amount']-$pay_type_two;
            }else{
                $use_yue = '|会员卡：('.$pay_type_two.')';
                $pty = $order['final_amount']-$pay_type_two;
            }

            if($pay_type == 1){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：支付宝（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 2){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：微信（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 3){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：会员卡（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 4){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：现金（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 5){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：银行卡（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 6){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：美团（'.$pty.'）'.$use_yue.'</td></tr>';
            }else if($pay_type == 7){
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：饿了么（'.$pty.'）'.$use_yue.'</td></tr>';
            }


            if(!empty($member)){            //显示会员信息
                if($post['yue'] <= $order['final_amount']){         //余额付款
                    $user_money = $member['user_money'] - $post['yue'];
                }else{
                    $user_money = $member['user_money'] - $order['final_amount'];
                }

                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：￥' . $member["mobile"] . '</td></tr>';
                $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $user_money . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
            }

            //新增数据 -- 2018-08-31  start
            $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">首次购物五折优惠</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">凭小票可享以下优惠</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/07-9/30 三⻆角形蛋糕全场半价</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/07-9/09 全场苏打水,⽔果茶,奶茶饮品1折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/10-9/16 全场苏打水,⽔果茶,奶茶饮品3折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/17-9/23 全场苏打水,水果茶,奶茶饮品5折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/24-9/30 全场苏打水,水果茶,奶茶饮品7折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">限时充值活动</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值100 送 20</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值200 送 80</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值500 送 200</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值1000 送 600</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值就送神秘卡券大礼包</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="3" style="text-align: left;font-size: smaller;">本次活动最终解释权归一朵餐饮有限公司所有</td></tr>';
            //新增数据结束 -- 2018-08-31  end

            $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">' . $store["address"] . '</td></tr>';
            $receipt .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
            $receipt .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';


            db('order')->where('id',$order['id'])->update(['pay_type'=>$pay_type,'pay_status'=>$pay_status,'pay_type_two'=>$pay_type_two,'pay_time'=>time(),'remark'=>'订单已完成','receipt'=>$receipt,'order_status'=>4]);
            db('order_details')->where('order_id',$order['id'])->update(['status'=>4]);

            $order_action = [
                'uid' => $order['uid'],
                'order_id' => $order['id'],
                'action_user' => 0,
                'order_status' => $order_status,
                'pay_status' => 1,
                'status_desc' => $remark,
                'storeid' => $order['store_id'],
                'addtime' => time(),
            ];
            db('order_action')->insert($order_action);                      //订单动作记录

            if ($pay_type == 1) {
                $fild = 'al_money';
            } else if ($pay_type == 2) {
                $fild = 'wx_money';
            } else if ($pay_type == 3) {          //余额
                $fild = 'user_money';
            } else if ($pay_type == 4) {
                $fild = 'xianjin_money';
            } else if ($pay_type == 5) {
                $fild = 'bank_money';
            } else if ($pay_type == 6) {
                $fild = 'meituan_money';
            } else if ($pay_type == 7) {
                $fild = 'elema_money';
            }

            if ($pay_status == 1) {               //加盟店或者订单支付完成
                if ($pay_type_two == 0) {         //全款支付
                    $pay_log_arr = [
                        'order_id' => $order['id'],
                        'order_sn' => $order['order_sn'],
                        'order_type' => 2,
                        'uid' => $order['uid'],
                        'store_id' => $order['store_id'],          //门店id
                        'pay_type' => $pay_type,
                        'pay_sign' => 1,
                        'amount' => $order['final_amount'],
                        'remark' => '线下购买商品，订单号' . $order["order_sn"] . '，总价：' . $order['final_amount'],
                        'addtime' => time()
                    ];
                    db('pay_log')->insert($pay_log_arr);            //新增支付记录
                    $store_goods_stock_arr = $this->get_store_goods_stock_log($order);
                    //更新商品库存
                    foreach ($store_goods_stock_arr as $k => $v) {
                        db('store_goods_stock')->where(['goods_id' => $v['goods_id'], 'goods_spec_id' => $v['goods_spec_id'], 'store_id' => $v['store_id'], 'is_deleted' => 0])->setDec('stock', $v['chuku_num']);
                        $store_goods_stock_arr[$k]['order_id'] = $order['id'];
                    }
                    db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $order['final_amount'],
                        'cur_credit' => $store['total_amount'] + $order['final_amount'],
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => $pay_type
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr['total_amount'] = $store['total_amount'] + $order['final_amount'];
                    $store_credit_arr[$fild] = $store[$fild] + $order['final_amount'];
                    if ($pay_type == 3) {             //余额全款支付
                        $store_credit_arr['credit'] = $store['credit'] + $order['final_amount'];      //更新门店转账余额
                    }
                    db('store')->where('id',$order['store_id'])->update($store_credit_arr);

                    if ($pay_type == 3) {         //使用余额支付
                        $data_wallet_arr = [
                            'uid' => $order['uid'],
                            'admin_id' => 0,
                            'store_id' => $order['store_id'],
                            'order_id' => $order['id'],
                            'order_sn' => $order['order_sn'],
                            'pay_time' => time(),
                            'pay_status' => 1,
                            'pay_type' => 3,
                            'amount' => $order['final_amount'],
                            'cur_amount' => $member['user_money'] - $order['final_amount'],
                            'sign' => 2,
                            'chargetype' => 1,
                            'charge_cn' => '支付订单',
                            'addtime' => time()
                        ];
                        //记录余额记录
                        db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                        db('user')->where('uid', $order['uid'])->setDec('user_money', $order['final_amount']);
                    }
                } else {
                    $log_money =  $order['final_amount'] - $pay_type_two;
                    $pay_log_arr1 = [
                        'order_id' => $order['id'],
                        'order_sn' => $order['order_sn'],
                        'order_type' => 2,
                        'uid' => $order['uid'],
                        'store_id' => $order['store_id'],          //门店id
                        'pay_type' => $pay_type,
                        'pay_sign' => 1,
                        'amount' => $log_money,
                        'remark' => '线下购买商品，订单号' . $order['order_sn'] . '，总价：' . $log_money,
                        'addtime' => time()
                    ];
                    $pay_log_arr2 = [
                        'order_id' => $order['id'],
                        'order_sn' => $order['order_sn'],
                        'order_type' => 2,
                        'uid' => $order['uid'],
                        'store_id' => $order['store_id'],          //门店id
                        'pay_type' => 3,
                        'pay_sign' => 1,
                        'amount' => $pay_type_two,
                        'remark' => '线下购买商品，订单号' . $order['order_sn'] . '，总价：' . $pay_type_two,
                        'addtime' => time()
                    ];
                    db('pay_log')->insert($pay_log_arr1);            //新增支付记录
                    db('pay_log')->insert($pay_log_arr2);            //新增支付记录

                    $data_wallet_arr = [
                        'uid' => $order['uid'],
                        'admin_id' => 0,
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'order_sn' => $order['order_sn'],
                        'pay_time' => time(),
                        'pay_status' => 1,
                        'pay_type' => 3,
                        'amount' => $pay_type_two,
                        'cur_amount' => $member['user_money'] - $pay_type_two,
                        'sign' => 2,
                        'chargetype' => 1,
                        'charge_cn' => '支付订单',
                        'addtime' => time()
                    ];
                    //记录余额记录
                    db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                    db('user')->where('uid', $order['uid'])->setDec('user_money', $pay_type_two);

//                db('store')->where('id',$store_id)->setInc('user_money',$pay_type_two);     //更新门店会员卡金额数量
                    //更新商品库存
                    $store_goods_stock_arr = $this->get_store_goods_stock_log($order);
                    foreach ($store_goods_stock_arr as $k => $v) {
                        db('store_goods_stock')->where(['goods_id' => $v['goods_id'], 'goods_spec_id' => $v['goods_spec_id'], 'store_id' => $v['store_id'], 'is_deleted' => 0])->setDec('stock', $v['chuku_num']);
                        $store_goods_stock_arr[$k]['order_id'] = $order['id'];
                    }
                    db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $log_money,
                        'cur_credit' => $store['total_amount'] + $log_money,
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => $pay_log_arr1['pay_type']
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money;
                    $store_credit_arr[$fild] = $store[$fild] + $log_money;
                    db('store')->where('id', $order['store_id'])->update($store_credit_arr);

                    $store_credit_log = [
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id'],
                        'type' => 1,
                        'credit' => $pay_type_two,
                        'cur_credit' => $store['total_amount'] + $log_money + $pay_type_two,
                        'remark' => '销售商品收入',
                        'addtime' => time(),
                        'order_type' => 1,
                        'order_sn' => $order['order_sn'],
                        'pay_type' => 3
                    ];
                    db('store_credit_log')->insert($store_credit_log);
                    $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money + $pay_type_two;
                    $store_credit_arr['credit'] = $store['credit'] + $pay_type_two;
                    $store_credit_arr['user_money'] = $store['user_money'] + $pay_type_two;
                    db('store')->where('id', $order['store_id'])->update($store_credit_arr);
                }

                if($order['coupon_id'] != 0){
                    db('user_ycard')->where(['coupon_id'=>$order['coupon_id'],'uid'=>$order['uid']])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
                }

                if(!empty($order['uid'])){
                    //变更积分
                    shouyintai_point($order['uid'],$order['final_amount'],$order['store_id'],$order['id'],$money=0,$order['order_sn'],1);
                }
                $this->success('支付成功，即将开启打印页面','',$receipt);
            }
        }else if($post['pay_type'] == 1){           //支付宝支付
            if($post['qrcode'] == ''){
                $this->error('请先扫描支付码','');
            }
            if(!empty($post['yue']) && !empty($order['uid'])){
                db('order')->where('id',$post['order_id'])->update(['pay_type_two'=>$post['yue']]);
            }
            $pay_result = $this->redirect(url('Aliguadan/pay').'?order_id='.$order['id']."&auth_code=".$post['qrcode']);
        }else if($post['pay_type'] == 2){          //微信支付
            if($post['qrcode'] == ''){
                $this->error('请先扫描支付码','');
            }
            if(!empty($post['yue']) && !empty($order['uid'])){
                db('order')->where('id',$post['order_id'])->update(['pay_type_two'=>$post['yue']]);
            }
            $pay_result = $this->redirect(url('Wxguadan/pay').'?order_id='.$order['id']."&auth_code=".$post['qrcode']);
        }
    }

    /**
     * @Author  lingyun
     * @Desc    创建门店商品库存记录数据
     * @param $order
     * @return mixed
     */
    private function get_store_goods_stock_log($order){
        $order_details = db('order_details')->alias('a')->join('ys_store_goods_stock b','a.store_goods_stock_id=a.id','LEFT')->where('a.order_id',$order['id'])->field('a.*,b.stock')->select();
        $store_goods_stock_log = [];
        foreach($order_details as $k => $v){
            //门店库存记录数据
            $store_goods_stock_arr[$k]['goods_id'] = $v['goods_id'];
            $store_goods_stock_arr[$k]['goods_spec_id'] = $v['spec_id'];
            $store_goods_stock_arr[$k]['title'] = $v['spec_detail'];
            $store_goods_stock_arr[$k]['store_id'] = $order['store_id'];
            $store_goods_stock_arr[$k]['order_id'] = '';
            $store_goods_stock_arr[$k]['types'] = 2;
            $store_goods_stock_arr[$k]['ruku_num'] = 0;
            $store_goods_stock_arr[$k]['tuihuo_num'] = 0;
            $store_goods_stock_arr[$k]['chuku_num'] = $v['goods_num'];
            $store_goods_stock_arr[$k]['sunhao_num'] = 0;
            $store_goods_stock_arr[$k]['remark'] = '售卖'.$v['goods_num'];
            $store_goods_stock_arr[$k]['cur_stock'] = $v['stock'] - $v['goods_num'];
            $store_goods_stock_arr[$k]['addtime'] = time();
            $store_goods_stock_arr[$k]['order_sn'] = $order['order_sn'];
        }

        return $store_goods_stock_arr;
    }


}
